package ex;

import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @Author: xwg
 * @CreateDate: 2023/4/9
 */


public class GoodConsumer implements Runnable {

    private BlockingQueue<Task> core = new ArrayBlockingQueue<>(4);
    private Map<String, List<EventListener>> obsContainer = new HashMap<>(10);

//    public boolean send(Task task) {
//        boolean r = core.offer(task);
//        return r;
//    }

    public void addEventListener(String queueName, EventListener observer) {
//        懒加载
        List<EventListener> observers = obsContainer.get(queueName);
        if (observers == null) {
            observers = new ArrayList<>();
            obsContainer.put(queueName, observers);
        }
        observers.add(observer);

    }

    public void emit(String queueName, Object... args) {
        List<EventListener> observers = obsContainer.get(queueName);
        if (observers != null) {
            Task task = new Task();
            task.queueName = queueName;
            task.params = args;
            core.offer(task);
        }
    }

    @Override
    public void run() {
        while (true) {
            Task t;
            try {
                t = core.take();
                List<EventListener> obs = obsContainer.get(t.queueName);
                if (obs != null) {
                    obs.forEach(x -> x.listen(t));
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        GoodConsumer goodConsumer = new GoodConsumer();
        OneArgument method1 = (one) -> {
            System.out.println("........单参数绑定事件 " + one);
        };
        MoreArgument method22 = (more) -> {
            System.out.println("........多参数绑定事件 " + more[0] + " more  " + more[1]);
        };
        goodConsumer.addEventListener("click", (e) -> {
            System.out.println("e click " + Arrays.toString(e.params));
            e.params[1] += "xx";
            method22.go(e.params[0], e.params[1]);

        });
        goodConsumer.addEventListener("click", (e) -> {
            System.out.println("e click2 " + Arrays.toString(e.params));
        });
        goodConsumer.addEventListener("avc", (e) -> {
            System.out.println("e avc " + Arrays.toString(e.params));
            method1.go((String) e.params[0]);
        });
        new Thread(goodConsumer, "good").start();
        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            while (true) {
                String next = scanner.next();
//                goodConsumer.send(task);
                goodConsumer.emit("click", next, "go");
                goodConsumer.emit("avc", next);
                goodConsumer.emit("mouseover", next);
            }
        }, "produce").start();
    }
}
